import Swal from 'sweetalert2/dist/sweetalert2.js'
import 'sweetalert2/src/sweetalert2.scss'
import './style.scss'

class YBPopView {

  static _showPop(title, type, other = {}) {
    Swal.fire({
      type: type,
      title: title,
      timer: 1500,
      showConfirmButton: false,
      width: '200px',
      ...other
    })
  }

  static msgSuccess (title, other) {
    this._showPop(title, 'success', other)
  }

  static msgError (title, other) {
    this._showPop(title, 'error', other)
  }

  static showInfo (title, other) {
    this._showPop(title, 'info', other)
  }

  static showQuestion (title, other) {
    this._showPop(title, 'question', other)
  }

  static showText (title, other) {
    this._showPop(title, null, other)
  }

  // 加载中
  static showLoading (title, other = {}) {
    Swal.fire({
      title,
      ...other,
      allowOutsideClick: false,
      onBeforeOpen: () => {
        Swal.showLoading()
      }
    })
  }

  // 关闭加载提示
  static hideLoading () {
    if (Swal.isLoading()) {
      Swal.close()
    }
  }

  /**
   * alert
   * @param title
   * @param msg
   * @param type warning, error, success, info, and question
   * @returns {Promise<any>}
   */
  static alert (title, msg, type) {
    return new Promise((resolve, reject) => {
      Swal.fire({
        title: title,
        text: msg,
        type: type,
        confirmButtonText: '确定'
      }).then(() => {
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  }

  // confirm
  /**
   *
   * @param title
   * @param msg
   * @param type warning, error, success, info, and question
   * @returns {Promise<any>}
   */
  static confirm (title, msg, other = {}) {
    return new Promise((resolve, reject) => {
      Swal.fire({
        title: title,
        text: msg,
        ...other,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then((result) => {
        if (result.value) {
          resolve()
        } else {
          reject()
        }
      }).catch((err) => {
        reject(err)
      })
    })
  }

  static prompt(title, msg, check) {
    return new Promise((resolve, reject) => {
      Swal.fire({
        title: title,
        text: msg,
        input: 'text',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        preConfirm: (text) => {
          if (check) {
            const data = check(text)
            if (data) {
              Swal.showValidationMessage(
                data
              )
            }
          }
        }
      }).then((result) => {
        if (result && result.dismiss) {
          reject(result)
        } else {
          resolve(result.value)
        }
      }).catch((err) => {
        reject(err)
      })
    })
  }
}

export default YBPopView

/*
text: 详情文字

onBeforeOpen: 显示前调用
onClose: 关闭的时候调用


 */
